package com.mofeng.myshop.service.impl;

import com.mofeng.myshop.domain.dto.CommodityCategoryDto;
import com.mofeng.myshop.domain.po.CommodityCategory;
import com.mofeng.myshop.domain.po.Project;
import com.mofeng.myshop.domain.po.base.BaseEntity;
import com.mofeng.myshop.domain.vo.CommodityCategoryVo;
import com.mofeng.myshop.mapper.CommodityCategoryMapper;
import com.mofeng.myshop.mapper.ProjectMapper;
import com.mofeng.myshop.service.ICommodityCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mofeng.myshop.service.PermissionService;
import com.mofeng.myshop.until.Constants;
import com.mofeng.myshop.until.MyUtil;
import com.mofeng.myshop.until.R;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品分类 服务实现类
 * </p>
 *
 * @author MoFeng
 * @since 2024-04-14
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class CommodityCategoryServiceImpl implements ICommodityCategoryService {

    private final CommodityCategoryMapper categoryMapper;

    private final ProjectMapper projectMapper;

    private final PermissionService permissionService;

    /**
     * 保存或者修改分类
     *
     * @param categoryDto 分类信息
     * @return 1
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveCategory(CommodityCategoryDto categoryDto) {
        CommodityCategory commodityCategory = categoryDto.toCommodityCategory();
        if (MyUtil.StringUtil.isEmpty(categoryDto.getId())) {
            return createCategory(commodityCategory);
        } else {
            return updateCategory(commodityCategory);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    protected R createCategory(CommodityCategory commodityCategory) {
        String name = commodityCategory.getName();
        if (MyUtil.StringUtil.isEmpty(name)) {
            return R.FAILED("分类名称不能为空");
        }

        Long projectId = commodityCategory.getProjectId();
        if (MyUtil.StringUtil.isEmpty(projectId)) {
            return R.FAILED("分类必须绑定项目");
        } else {
            Project project = projectMapper.selectById(projectId);
            if (project == null) {
                return R.FAILED("找不到此项目");
            }
        }

        Long parentId = commodityCategory.getParentId();
        if (!MyUtil.StringUtil.isEmpty(parentId)) {
            CommodityCategory categoryParent = categoryMapper.selectById(parentId);
            if (categoryParent == null) {
                return R.FAILED("找不到父级分类");
            }
        }
        Integer groupNumber = commodityCategory.getGroupNumber();
        if (MyUtil.StringUtil.isEmpty(groupNumber)) {
            commodityCategory.setGroupNumber(1);
        }

        String hasPic = commodityCategory.getHasPic();
        if (MyUtil.StringUtil.isEmpty(hasPic)) {
            commodityCategory.setHasPic(Constants.State.DEFAULT_STATE);
        }
        String hasMultiplier = commodityCategory.getHasMultiplier();
        if (MyUtil.StringUtil.isEmpty(hasMultiplier)) {
            commodityCategory.setHasMultiplier(Constants.State.DEFAULT_STATE);
        }
        String unit = commodityCategory.getUnit();
        if (MyUtil.StringUtil.isEmpty(unit)) {
            commodityCategory.setUnit("个");
        }
        commodityCategory.setDelete(Constants.State.DEFAULT_STATE);
        commodityCategory.setShow(Constants.State.DEFAULT_STATE);
        commodityCategory.setOpen(Constants.State.DEFAULT_STATE);
        categoryMapper.insert(commodityCategory);
        return R.SUCCESS("分类添加成功").setData(new CommodityCategoryVo(commodityCategory));
    }

    @Transactional(rollbackFor = Exception.class)
    protected R updateCategory(CommodityCategory commodityCategory) {
        Long projectId = commodityCategory.getProjectId();
        if (!MyUtil.StringUtil.isEmpty(projectId)) {
            Project project = projectMapper.selectById(projectId);
            if (project == null) {
                return R.FAILED("找不到此项目");
            }
        }

        Long parentId = commodityCategory.getParentId();
        if (!MyUtil.StringUtil.isEmpty(parentId)) {
            CommodityCategory categoryParent = categoryMapper.selectById(parentId);
            if (categoryParent == null) {
                return R.FAILED("找不到父级分类");
            }
        }
        categoryMapper.updateById(commodityCategory);
        return R.SUCCESS("分类修改成功").setData(new CommodityCategoryVo(commodityCategory));
    }

    /**
     * 删除分类信息
     *
     * @param ids ids
     * @return 1
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R delCategory(List<String> ids) {
        categoryMapper.deleteBatchIds(ids);
        return R.SUCCESS("分类删除完成");
    }

    /**
     * 获取分类信息
     *
     * @param id id
     * @return 1
     */
    @Override
    public R getCategory(String id) {
        CommodityCategory commodityCategory = categoryMapper.selectById(id);
        return R.SUCCESS("分类查询成功").setData(new CommodityCategoryVo(commodityCategory));
    }

    /**
     * 获取分类列表
     *
     * @param projectId 项目的ID
     * @return 1
     */
    @Override
    public R getCategoryList(String projectId) {
        boolean master = permissionService.MASTER();
        List<CommodityCategory> commodityCategories = null;
        Long projectIdLong = MyUtil.NumberUtil.asLong(projectId);
        if (master) {
            commodityCategories = categoryMapper.findList(projectIdLong, null);
        } else {
            commodityCategories = categoryMapper.findList(projectIdLong, Constants.State.DEFAULT_STATE);
        }
        List<Project> projectListFromDB = projectMapper.findAll();
        //封装项目
        if (projectListFromDB != null) {
            Map<Long, List<Project>> projectMap = projectListFromDB.stream().collect(Collectors.groupingBy(BaseEntity::getId));
            for (CommodityCategory commodityCategory : commodityCategories) {
                Long projectItemId = commodityCategory.getProjectId();
                List<Project> projectList = projectMap.get(projectItemId);
                if (projectList != null) {
                    commodityCategory.setProject(projectList.get(0));
                }
            }
        }
        return R.SUCCESS().setData(CommodityCategoryVo.change(commodityCategories));
    }
}
